#include "include/market_data_manager.hpp"
#include "include/tools/readAndWrite.hpp"
#include <QDebug>
#include <QFile>
#include <QJsonArray>
#include <QJsonDocument>
#include <QJsonObject>
#include <chrono>
#include <iomanip>
#include <sstream>

MarketDataManager::MarketDataManager(QObject *parent)
    : QObject(parent), m_isSimulating(false) {
  m_timer = new QTimer(this);
  connect(m_timer, &QTimer::timeout, this, [this]() {
    // 更新所有股票价格
    for (auto &stock : m_stocks) {
      stock.updatePrice();
    }
    // 发出市场更新信号
    emit marketUpdated();
  });
}

MarketDataManager::~MarketDataManager() {
  stopSimulation();
  if (m_timer) {
    delete m_timer;
    m_timer = nullptr;
  }
  try {
    nlohmann::json stocksWaitStore;
    // 将当前股票数据保存到 JSON 文件
    for (const auto &stock : m_stocks) {
      nlohmann::json stockJson;
      stockJson["code"] = stock.code.toStdString();
      stockJson["name"] = stock.name.toStdString();
      stockJson["price"] = stock.price;
      stockJson["change"] = stock.change;
      stocksWaitStore["stocks"].push_back(stockJson);
    }

    // 获取当前时间并格式化为年月日时分秒、毫秒
    auto now = std::chrono::system_clock::now();
    auto time_t_now = std::chrono::system_clock::to_time_t(now);
    std::tm *tm_now = std::localtime(&time_t_now);

    // 计算毫秒部分
    auto ms = std::chrono::duration_cast<std::chrono::milliseconds>(
                  now.time_since_epoch()) %
              1000;

    // 格式化时间字符串
    std::ostringstream time_ss;
    time_ss << std::put_time(tm_now, "%Y年%m月%d日%H时%M分%S秒") << ","
            << std::setfill('0') << std::setw(3) << ms.count() << "毫秒";

    stocksWaitStore["time"] = time_ss.str();
    // 使用 readAndWrite.hpp 中的函数写入 JSON 文件
    std::string stdFilePath = "data/stocks.json";
    write_to_file(stdFilePath, stocksWaitStore);
  } catch (const std::exception &e) {
    qDebug() << "MarketDataManager析构函数异常:" << e.what();
  }
}

bool MarketDataManager::loadStocks(const QString &filePath) {
  nlohmann::json stocksJson;

  try {
    // 使用 readAndWrite.hpp 中的函数读取 JSON 文件
    std::string stdFilePath = filePath.toStdString();
    stocksJson = read_from_file(stdFilePath, stocksJson);

    // 清空现有股票列表
    m_stocks.clear();

    // 解析股票数据
    if (stocksJson.contains("stocks") && stocksJson["stocks"].is_array()) {
      auto stocksArray = stocksJson["stocks"];

      for (const auto &stockJson : stocksArray) {
        if (stockJson.contains("code") && stockJson.contains("name") &&
            stockJson.contains("price") && stockJson.contains("change")) {

          QString code =
              QString::fromStdString(stockJson["code"].get<std::string>());
          QString name =
              QString::fromStdString(stockJson["name"].get<std::string>());
          double price = stockJson["price"].get<double>();
          double change = stockJson["change"].get<double>();

          Stock stock(code, name, price);
          stock.change = change;
          m_stocks.append(stock);
        }
      }

      qDebug() << "已加载" << m_stocks.size() << "支股票";
      return true;
    }
  } catch (const std::exception &e) {
    qDebug() << "加载股票数据失败:" << e.what();
  }

  return false;
}

bool MarketDataManager::saveStocks(const QString &filePath) {
  try {
    nlohmann::json stocksJson;
    nlohmann::json stocksArray = nlohmann::json::array();

    for (const auto &stock : m_stocks) {
      nlohmann::json stockJson;
      stockJson["code"] = stock.code.toStdString();
      stockJson["name"] = stock.name.toStdString();
      stockJson["price"] = stock.price;
      stockJson["change"] = stock.change;

      stocksArray.push_back(stockJson);
    }

    stocksJson["stocks"] = stocksArray;

    // 获取当前时间并格式化为年月日时分秒、毫秒
    auto now = std::chrono::system_clock::now();
    auto time_t_now = std::chrono::system_clock::to_time_t(now);
    std::tm *tm_now = std::localtime(&time_t_now);

    // 计算毫秒部分
    auto ms = std::chrono::duration_cast<std::chrono::milliseconds>(
                  now.time_since_epoch()) %
              1000;

    // 格式化时间字符串
    std::ostringstream time_ss;
    time_ss << std::put_time(tm_now, "%Y年%m月%d日%H时%M分%S秒") << ","
            << std::setfill('0') << std::setw(3) << ms.count() << "毫秒";

    stocksJson["time"] = time_ss.str();

    // 使用 readAndWrite.hpp 中的函数写入 JSON 文件
    std::string stdFilePath = filePath.toStdString();
    write_to_file(stdFilePath, stocksJson);

    qDebug() << "已保存" << m_stocks.size() << "支股票";
    return true;
  } catch (const std::exception &e) {
    qDebug() << "保存股票数据失败:" << e.what();
  }

  return false;
}

void MarketDataManager::startSimulation(int interval) {
  if (!m_isSimulating) {
    m_timer->start(interval);
    m_isSimulating = true;
    qDebug() << "市场模拟已启动，更新间隔:" << interval << "毫秒";
  }
}

void MarketDataManager::stopSimulation() {
  if (m_isSimulating) {
    m_timer->stop();
    m_isSimulating = false;
    qDebug() << "市场模拟已停止";
  }
}

QVector<Stock> &MarketDataManager::getStocks() { return m_stocks; }

const QVector<Stock> &MarketDataManager::getStocks() const { return m_stocks; }

Stock *MarketDataManager::findStock(const QString &code) {
  for (auto &stock : m_stocks) {
    if (stock.code == code) {
      return &stock;
    }
  }
  return nullptr;
}
